首先回顧一下 DAY15 的畫面
我會以分類的角度當作資料搜尋的切入點,分類->商品->商品影片、商品演員、商品特色,以這樣的順序來將資料讀取出來,這次會用昨天講到的 Route、Controller、Service、Repository、Model、Resource、Response 這些層級來完成API。
在 Laravel 的框架裡,Route、Response 是已經內建好了不需要在創建的,Controller、Model、Resource 則是可以利用 php artisan make 的指令來建立,而 Service 、Repository 則是要用指令 mkdir touch 來自行建立,再自行建立的過程中記得 Class name 必須與檔案名稱相同,並且要填寫正確的 namespace 後續才能順利引用。
Controller:
<?php
namespace App\Http\Controllers;
use App\Services\CategoryService;
use App\Http\Resources\CategoryResource;
class CategoryController extends Controller
{
protected $categoryService;
public function __construct(CategoryService $categoryService)
{
$this->categoryService = $categoryService;
}
public function index()
{
$categories = $this->categoryService->index();
return response()->json(CategoryResource::collection($categories));
}
}
Service:
<?php
namespace App\Services;
use App\Repositories\CategoryRepository;
class CategoryService
{
protected $categoryRepository;
public function __construct(CategoryRepository $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function index()
{
return $this->categoryRepository->index();
}
}
Repository:
<?php
namespace App\Repositories;
use App\Models\Category;
class CategoryRepository
{
public function index()
{
return Category::with('products')
->with('products.video')
->with('products.characteristic')
->with('products.actor')
->get();
}
}
Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
今日時間有限,明天會搭配 Feature Test 來確認 API 是否正常。